package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.dao.impl.JdbcAccoutDaoImpl;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.TransactionManager;

public class TransferServiceImpl implements TransferService {

    private AccountDao accountDao = new JdbcAccoutDaoImpl();

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        try {
            // 开启事务
//            ConnectionUtils.getInstance().getCurrentThreadConn().setAutoCommit(false);
            TransactionManager.getInstance().beginTransaction();

            Account from = accountDao.queryAccountByCardNo(fromCardNo);
            Account to = accountDao.queryAccountByCardNo(toCardNo);
            from.setMoney(from.getMoney()-money);

            int c = 1/0;
            to.setMoney(to.getMoney()+money);
            accountDao.updateAccountByCardNo(from);
            accountDao.updateAccountByCardNo(to);

            // 提交事务
//            ConnectionUtils.getInstance().getCurrentThreadConn().commit();
            TransactionManager.getInstance().commit();

        } catch (Exception e) {
            e.printStackTrace();

            // 回滚事务
//            ConnectionUtils.getInstance().getCurrentThreadConn().rollback();
            TransactionManager.getInstance().rollback();

            throw e;
        }


    }
}
